<?php

use Doraemon\tools\Log;


/**
 * Class ErpActionPlugin
 * @method \Yaf_Request_Abstract getRequest () : Yaf_Request_Abstract
 * @method \Yaf_Response_Abstract getResponse () : Yaf_Response_Abstract
 */
abstract class ErpActionPlugin extends \Yaf_Action_Abstract
{

    const LOGIN_AUTH = false;

    const CODE_SUCCESS = 1;

    const CODE_NOT_RETRY = -1;

    abstract public function main();

    public function execute()
    {
        $this->getResponse()->setHeader('Content-Type', 'application/json;charset=utf8');
        try {

            $this->checkModules();
            $this->main();
        } catch (\Exception $e) {
            $this->setError($e->getCode(), $e->getMessage(), $e->getLine());
        }
    }

    protected function checkModules()
    {
        if (isset($_SERVER['APP_MODULES'])) {
            $authorizedModules = explode(",", $_SERVER['APP_MODULES']);
            if (!in_array($this->getModuleName(), $authorizedModules)) {
                throw new \Exception("当前域名不能请求当前模块");
            }
        }
    }

    protected function setSuccess($data = NULL)
    {
        $this->getResponse()->setBody(json_encode([
            "code" => self::CODE_SUCCESS,
            "data" => $data
        ], JSON_UNESCAPED_UNICODE));
    }

    protected function setError($code, $message, $line = 0)
    {
        $from = $this->getRequest()->getPost("from");


        if(empty($from)){
            if ($code == self::CODE_NOT_RETRY) {
                $view = [
                    "code" => self::CODE_SUCCESS,
                    "msg" => $message
                ];
            } else {
                $view = [
                    "code" => $line,
                    "msg" => $message
                ];
            }
        }else{
            $view = [
                "code" => -2,//有来源方向的区别有错误异常的code
                "msg" => $message
            ];
        }

        $post = $this->getRequest()->getPost();
        $body = file_get_contents("php://input");
        Log::debug('erp请求响应', compact('view', 'post', 'body'));
        $this->getResponse()->setBody(json_encode($view, JSON_UNESCAPED_UNICODE));
    }
}
